import { DragDropContext, DropResult } from 'react-beautiful-dnd';
import React, { useState, useEffect } from 'react';
import Transfer from '@/views/Transfer';
import EndSession from '@/views/EndSession';
import SendCommand from '../SendCommand';
import styled from '@emotion/styled';
import ToolList from './ToolList';
import { useMenuContext } from '../Context/MenuContext';
import { saveAgentProfile } from '@/api';
import AgentService from '@/modules/Agent';
import { useSelector } from 'react-redux';
import TTS from '../TTS';
import { useTranslation } from 'react-i18next';
import CollectVariable from '../CollectVariable';
import CardCollect from '../CardCollect';
import KnowledgeBase from '../KnowledgeBase';

const Root = styled.div`
	background-color: #fff;
	box-sizing: border-box;
	padding: 10px;
	display: flex;
	flex-direction: column;
`;

const DescTips = styled.p`
	height: 30px;
	color: #868686;
	font-size: 14px;
	cursor: default;
`;

const ToolBar = (props: { hangup ?: (reason: string) => void }) => {
	const { t } = useTranslation();
	const { tools, setTools } = useMenuContext();
	const { session } = useSelector((state: any) => state);
	const { hangup } = props;
	const onDragStart = (data: any) => {
		setActiveIdx(data.source.index);
	};
	const onDragUpdate = () => {};

	const onDragEnd = (result: DropResult) => {
		if (!result.destination) {
			return;
		}

		if (result.destination.index === result.source.index) {
			return;
		}
		const sortTools = reorder(tools(), result.source.index, result.destination.index);
		setTools(sortTools);
		saveTools(sortTools);
	};

	const saveTools = async (tools: any[]) => {
		try {
			const saveToolIds = tools.map((item: any) => item.id);
			const data = await saveAgentProfile(saveToolIds);
			if (data.status === 200) {
				console.log(data, 'save tools success');
			}
		} catch (error) {
			console.log(error, 'save tools error');
		}
	};

	const [activeIdx, setActiveIdx] = useState<number>(-1);

	/** 重拍顺序 */
	const reorder = (list: any[], startIndex: number, endIndex: number): any[] => {
		const result = Array.from(list);
		const [removed] = result.splice(startIndex, 1);
		result.splice(endIndex, 0, removed);
		return result;
	};

	const { menuState, setMenuState, bizScenarioTransfer, onChangeBizScenario, onEndSession, inviteAgent, agentTransfer } = useMenuContext();

	useEffect(() => {
		if (!session.sessionId || !AgentService.sessionId) {
			setMenuState({ ...menuState, showSendCommand: false, showTransfer: false, showVariableView: false, showKnowledgeBase: false });
		}
	}, [session.sessionId, AgentService.sessionId]);

	return (
		<>
			{/* 菜单栏 */}
			<DragDropContext onDragStart={onDragStart} onDragUpdate={onDragUpdate} onDragEnd={onDragEnd}>
				<Root>
					<ToolList internalScroll listType="MENU-TOOL" list={tools() || []} activeIdx={activeIdx} />
				</Root>
			</DragDropContext>
			{tools().length >= 7 ? <DescTips>{'* ' + t('long-press-drag-sorting')}</DescTips> : <DescTips></DescTips>}
			{/* 转接 */}
			<Transfer
				visible={menuState.showTransfer}
				searchAgentBindBizScenario={menuState.searchAgentBindBizScenario}
				fields={menuState.fields}
				title={menuState.modalTitle}
				transferError={menuState.transferError}
				inviteOtherStatus={menuState.inviteMode}
				inviteAgentError={menuState.inviteAgentError}
				groupSkillError={menuState.groupSkillError}
				bizScenarioTransferToScenErrorText={menuState.bizScenarioTransferToScenErrorText}
				bizScenarioTransferToAgentErrorText={menuState.bizScenarioTransferToAgentErrorText}
				transferAgentIdErrorText={menuState.transferAgentIdErrorText}
				bizScenarioTransferGroupSkill={menuState.bizScenarioTransferGroupSkill}
				onClose={() => {
					setMenuState({
						...menuState,
						showTransfer: false,
						transferError: false,
						inviteAgentError: '',
						groupSkillError: '',
						bizScenarioTransferToScenErrorText: '',
						bizScenarioTransferToAgentErrorText: '',
						bizScenarioTransferGroupSkill: '',
						transferAgentIdErrorText: ''
					});
				}}
				bizScenarioTransfer={bizScenarioTransfer}
				inviteAgent={inviteAgent}
				agentTransfer={agentTransfer}
				onChangeBizScenario={onChangeBizScenario}
			/>
			{/* 结束会话 */}
			<EndSession
				visible={menuState.endSessionView}
				onClose={() => {
					setMenuState({ ...menuState, endSessionView: false });
				}}
				onOk={() => onEndSession('')}
			/>
			<SendCommand
				visible={menuState.showSendCommand && menuState.sendCommandModalType !== 'sendCardCollection'}
				showCustomerRoleOrName={menuState.showCustomerRoleOrName}
				sendCommandModalType={menuState.sendCommandModalType}
				onClose={() => {
					setMenuState({ ...menuState, showSendCommand: false });
				}}
				onOk={() => {
					setMenuState({ ...menuState, showSendCommand: false });
				}}
			/>
			<CollectVariable visible={menuState.showVariableView} />
			<TTS />
			<CardCollect
				visible={menuState.showSendCommand && menuState.sendCommandModalType === 'sendCardCollection'}
				showCustomerRoleOrName={menuState.showCustomerRoleOrName}
				sendCommandModalType={menuState.sendCommandModalType}
				onClose={() => {
					setMenuState({ ...menuState, showSendCommand: false });
				}}
				onOk={() => {
					setMenuState({ ...menuState, showSendCommand: false });
				}}
			/>
			{menuState.showKnowledgeBase && (
				<KnowledgeBase
					visible={menuState.showKnowledgeBase}
					showCustomerRoleOrName={menuState.showCustomerRoleOrName}
					close={() => {
						setMenuState({ ...menuState, showKnowledgeBase: false });
					}}
				/>
			)}
		</>
	);
};

export default ToolBar;
